package com.kaibai.controller;

import com.kaibai.pojo.User;
import com.kaibai.service.UserService;
import com.kaibai.service.impl.UserServiceImpl;
import com.kaibai.utils.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class registerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String name = request.getParameter("name");
//        String age = request.getParameter("age");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
//        String email = request.getParameter("email");
//        String sex = request.getParameter("sex");
        String code = request.getParameter("code");

        if(token != null && token.equalsIgnoreCase(code)){
            if(password.equals(repassword)){
                UserService service = new UserServiceImpl();
                if(service.existsUsername(name)){
                    //用户名已存在，不可用
                    response.getWriter().write("用户名"+ name +"已存在");
                    //response.sendRedirect(request.getContextPath()+"/jsp/user/register.jsp");
                    response.sendRedirect(request.getContextPath()+"/jsp/user/login1.jsp");
                }else{
                    //用户名不存在，可用
                    User user = WebUtil.copyParamToBean(request.getParameterMap(),new User());


                    service.insert(user);
                    //service.insert(new User(name,Integer.valueOf(age),email,sex,password));
                    //response.sendRedirect(request.getContextPath()+"/jsp/user/login.jsp");
                    response.sendRedirect(request.getContextPath()+"/jsp/user/login1.jsp");
                }
            }else{
                response.getWriter().write("两次密码不一致");
                //response.sendRedirect(request.getContextPath()+"/jsp/user/register.jsp");
                response.sendRedirect(request.getContextPath()+"/jsp/user/login1.jsp");
            }
        }else if(token != null && !token.equalsIgnoreCase(code)){
            response.getWriter().write("验证码"+code+"不正确");
            response.sendRedirect(request.getContextPath()+"/jsp/user/register.jsp");
        }else{
            response.sendRedirect(request.getContextPath()+"/jsp/user/login.jsp");
        }


    }
}
